package com.ambitor.grass.util.date;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;

public class DateUtils {
	
	public static Timestamp encodeTimestamp(String timeStr) throws Exception {
		String format = getTimestampFormat(timeStr);
		return encodeTimestamp(format, timeStr);
	}
	
	public static Timestamp encodeTimestamp(String format, String timeStr) throws Exception {
		if (null == timeStr || "".equals(timeStr))return null;
		if (format.length() != timeStr.length()) format = getTimestampFormat(timeStr);
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return new Timestamp(sdf.parse(timeStr).getTime());
	}
	
	public String decodeTimestamp(String format, String timeStr) throws Exception {
		Timestamp time = encodeTimestamp(format, timeStr);
		return decodeTimestamp(format, time);
	}
	
	public String decodeTimestamp(String format, Timestamp time) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(time);
	}
	
	public static String getTimestampFormat(String value) {
		switch (value.length()) {
			case 4:
				return "yyyy";
			case 6:
				return "yyyyMM";
			case 7:
				return "yyyy-MM";
			case 8:
				return "yyyyMMdd";
			case 10:
				return "yyyy-MM-dd";
			case 13:
				return "yyyy-MM-dd HH";
			case 16:
				return "yyyy-MM-dd HH:mm";
			case 19:
				return "yyyy-MM-dd HH:mm:ss";
			case 21:
				return "yyyy-MM-dd HH:mm:ss.S";
		}
		return null;
	}
}
